package com.luzhikun.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/*
 * @Author liu-miss
 * @Description 防止恶意登录
 * @Date 8:33 2021/5/8
 **/
@WebFilter(filterName = "LoginFilter",value = "/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 获取请求对象
        HttpServletRequest req=(HttpServletRequest) request;
        // 获取当前用户的session（如果没有不创建）
        HttpSession session = req.getSession(false);
        //1.调用请求对象读取请求协议包中的URI，了解用户访问的资源文件
        // URI[/网站名/资源文件名称]
        String requestURI = req.getRequestURI();
        System.out.println(requestURI);
        // 判断当前用户是否合法
        if (requestURI.indexOf("login")!=-1 || "/myWeb/".equals(requestURI) || session!=null){
            // 放行
          chain.doFilter(request,response);
        }
        // 拒绝请求
        if (session==null){
            req.getRequestDispatcher("/login_error.jsp").forward(request,response);
            return;
        }
    }

    @Override
    public void destroy() {

    }
}
